package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import yxy.apple.util.RandomUtility;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.actsecret;
import yxy.cherry.data.bean.actsecretcharge;
import yxy.cherry.data.bean.actsecretreward;
import yxy.cherry.data.bean.task;
import yxy.game.pm2.active.ActiveUtil;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.subordinateclass.randomTaskid;
import yxy.game.pm2.active.module.subordinateclass.zztask;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.PlayerModule;
import yxy.game.pm2.bean.task.Task;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.module.task.TaskHandle;
import yxy.game.pm2.module.tip.TipHandle;
import yxy.game.pm2.module.tip.TipType;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ActiveModule_征战日志 extends PlayerModule {

	//bean -----------------------------------------------------------	
	public static final int acttype = 5;
	
	private DateTime playercreate;	//玩家创建时间
	private int round;		//轮次
	private int runday;
	private DateTime end;
	private int zzexp;	//征战经验
	private ArrayList<Integer> zzrewards = new ArrayList<Integer>();	//征战经验已获取奖励id list
	private int payamount;	//充值经验
	private ArrayList<Integer> payrewards = new ArrayList<Integer>();	//充值已获取奖励id list
	private HashMap<String, zztask> runningcodetaskmap = new HashMap<String, zztask>();		//进行中任务
	private HashMap<String, zztask> overtimecodetaskmap = new HashMap<String, zztask>();	//超时任务map
	
	public DateTime getPlayercreate() {
		return playercreate;
	}
	public void setPlayercreate(DateTime playercreate) {
		this.playercreate = playercreate;
	}
	public int getRound() {
		return round;
	}
	public void setRound(int round) {
		this.round = round;
	}
	public int getRunday() {
		return runday;
	}
	public void setRunday(int runday) {
		this.runday = runday;
	}
	public DateTime getEnd() {
		return end;
	}
	public void setEnd(DateTime end) {
		this.end = end;
	}
	public int getZzexp() {
		return zzexp;
	}
	public void setZzexp(int zzexp) {
		this.zzexp = zzexp;
	}
	public ArrayList<Integer> getZzrewards() {
		return zzrewards;
	}
	public void setZzrewards(ArrayList<Integer> zzrewards) {
		this.zzrewards = zzrewards;
	}
	public int getPayamount() {
		return payamount;
	}
	public void setPayamount(int payamount) {
		this.payamount = payamount;
	}
	public ArrayList<Integer> getPayrewards() {
		return payrewards;
	}
	public void setPayrewards(ArrayList<Integer> payrewards) {
		this.payrewards = payrewards;
	}
	public HashMap<String, zztask> getRunningcodetaskmap() {
		return runningcodetaskmap;
	}
	public void setRunningcodetaskmap(HashMap<String, zztask> runningcodetaskmap) {
		this.runningcodetaskmap = runningcodetaskmap;
	}
	public HashMap<String, zztask> getOvertimecodetaskmap() {
		return overtimecodetaskmap;
	}
	public void setOvertimecodetaskmap(HashMap<String, zztask> overtimecodetaskmap) {
		this.overtimecodetaskmap = overtimecodetaskmap;
	}

	//func ------------------------------------------------------------
	
//	public static final int canget = 1;
//	public static final int hadget = 2;
//	public static final int cannotget = 3;
	
	/** 添加充值经验 **/
	public void addPayamount(int addpayamount) {
		//核对天数
		if(getRunday() > 7) {
			int payamount = getPayamount();
			payamount = payamount + addpayamount;
			setPayamount(payamount);
			set();			
		}
	}
	
	/** 创建实例 **/
	private static ActiveModule_征战日志 create(String playerCode) {
		PlayerBean pb = PlayerBean.get(playerCode);

		ActiveModule_征战日志 am = new ActiveModule_征战日志();
		am.setPlayercreate(pb.getCreateTime());
		am.setRunday(1);
		am.setRound(1);
		am.setEnd(getrunendtime(1));
		am.setPlayerCode(playerCode);
		am.setPayamount(0);
		am.setZzexp(0);
		am.set();
		return am;
	}
	
	//刷新 重新开启
	private void reset() {
		//删除进行中任务
		Map<String, zztask> runzztaskmap = getRunningcodetaskmap();
		Task.remove(getPlayerCode(), runzztaskmap.keySet());
		
		//重新计算结束
		setEnd(getrunendtime(1));
		
		setRunday(1);
		setPayamount(0);
		setZzexp(0);
		setPayrewards(new ArrayList<Integer>());
		setRunningcodetaskmap(new HashMap<String, zztask>());
		setZzrewards(new ArrayList<Integer>());
		set();
	}
	
	/** 创建任务 **/
	private ArrayList<zztask> createTasks() {
		ArrayList<zztask> tasks = new ArrayList<zztask>();
		// 创建任务
		Map<String, actsecret> ascmap = ActDataCenter.getAllData(actsecret.class, getPlayerCode());
		for (String key : ascmap.keySet()) {
			actsecret asc = ascmap.get(key);
			int[] taskids = asc.getTaskid();
			int[] weights = asc.getPercent();
			ArrayList<randomTaskid> randtaskids = new ArrayList<randomTaskid>();
			for (int i = 0; i < taskids.length; i++) {
				int taskid = taskids[i];
				int weight = weights[i];
				randomTaskid randtaskid = new randomTaskid(taskid, weight);
				randtaskids.add(randtaskid);
			}
			randomTaskid randomtaskid = RandomUtility.randomWeight(randtaskids); // 权重随机

			zztask zt = new zztask();
			zt.setId(asc.getId());
			zt.setTaskid(randomtaskid.getTaskid());
			zt.setPosition(asc.getPosition());
			zt.setAddzzexp(asc.getIntegral());

			task taskdata = DataCenter.getData(randomtaskid.getTaskid(), task.class);
			if (taskdata == null) {
				continue;
			}
			Task taskbean = Task.create(getPlayerCode(), taskdata);

			zt.setTaskcode(taskbean.getCode());
			getRunningcodetaskmap().put(zt.getTaskcode(), zt);
			tasks.add(zt);
		}
		return tasks;
	}
	
	/**
	 * 转天刷新任务
	 */
	private void refreshDayTask() {
		//删除进行中任务
		Map<String, zztask> runzztaskmap = getRunningcodetaskmap();
		Task.remove(getPlayerCode(), runzztaskmap.keySet());
		
		setRunningcodetaskmap(new HashMap<String, zztask>());
		createTasks();
	}
	
	/** 更新 **/
	private void update() {
		if(getOvertimecodetaskmap().size() > 0) {
			Task.remove(getPlayerCode(), getOvertimecodetaskmap().keySet());
			setOvertimecodetaskmap(new HashMap<String, zztask>());
			set();
		}

		if(getPlayercreate() == null) {
			PlayerBean pb = PlayerBean.get(getPlayerCode());
			setPlayercreate(pb.getCreateTime());
			set();
		}
		
		if(getRound() != getround()) {
			setRound(getround());
			reset();
		}
		
		if(getRunday() != getrunday()) {
			int runday = getrunday();
			setRunday(runday);
			
			if(runday > 7) {
				refreshDayTask();	
				set();
				
				TaskHandle.handle(getPlayerCode(), TaskType.统计型_登录_次数, 1);
			}
		}
		
		//核对结束时间
		if(getEnd() == null) {
			setEnd(getrunendtime(getrunday()));
			set();
		}else {
			if(!getEnd().isEqual(getrunendtime(getrunday()))) {
				setEnd(getrunendtime(getrunday()));
				set();
			}
		}
		
	}
	
	/**
	 * 获取循环内运行天数		1-7 关闭  8-14 开启
	 * @param start
	 * @return	
	 */
	private int getrunday() {
		if(getPlayercreate() == null) {
			PlayerBean pb = PlayerBean.get(getPlayerCode());
			setPlayercreate(pb.getCreateTime());
			set();
		}
		
		int days = ActiveUtil.days(getPlayercreate(), DateTime.now());
		int runday = days % 14 + 1;
		return runday;
	}
	
	private int getround() {
		int days = ActiveUtil.days(getPlayercreate(), DateTime.now());
		int round = days / 14 + 1;
		return round;
	}
	
	/**
	 * 计算单个循环内活动结束时间	
	 * @param runday
	 * @return
	 */
	public static DateTime getrunendtime(int runday) {
		DateTime now = DateTime.now();
		int surplusdays = 14 - runday;
		DateTime end = now.plusDays(surplusdays).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(0);
		return end;
	}
	
	//redis -----------------------------------------------
	
	/** 获取redis key **/
	static private String key(String playerCode) {
		return String.format("PLAYER:%s:ACTIVE:%S", playerCode, acttype);
	}

	/** 保存 **/
	public void set() {
		try {
			setv(key(getPlayerCode()), this);
			check();
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取ActiveModule_征战日志
	 * @param playerCode
	 * @return
	 */
	static public ActiveModule_征战日志 get(String playerCode, Boolean isNewPlayer) {
		try {
			ActiveModule_征战日志 module = getv(key(playerCode));
			if (module == null) {

				//新用户不需要去查数据库
				if(!isNewPlayer){
					module = MySQLCacheDAO.getV(key(playerCode), ActiveModule_征战日志.class);
					if(module != null){module.set();}//同步到redis
				}


				if (module == null) {
					module = create(playerCode);
				}
				if(module == null){return null;}
			}

			module.update();
			module.check();
			return module;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/** 检查红点，活动是否开启 **/
	public void check() {
		
		if(getrunday() > 7) {
			new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.开启);
		}else {
			new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
			new TipHandle().updateTip(getPlayerCode(), TipType.活动_征战日志奖励, false);
			return;
		}
		
		//充值奖励能否领取
		Map<String, actsecretcharge> ascmap = ActDataCenter.getAllData(actsecretcharge.class, getPlayerCode());
		for(String key : ascmap.keySet()) {
			actsecretcharge asc = ascmap.get(key);
			if(getPayrewards().contains(asc.getId())) {
				continue;
			}
			if(getPayamount() >= asc.getCondition()) {
				new TipHandle().updateTip(getPlayerCode(), TipType.活动_征战日志奖励, true);
				return;
			}
		}
		
		//经验奖励能否领取
		Map<String, actsecretreward> asrmap = ActDataCenter.getAllData(actsecretreward.class, getPlayerCode());
		for(String key : asrmap.keySet()) {
			actsecretreward asr = asrmap.get(key);
			if(getZzrewards().contains(asr.getId())) {
				continue;
			}
			if(getZzexp() >= asr.getCondition()) {
				new TipHandle().updateTip(getPlayerCode(), TipType.活动_征战日志奖励, true);
				return;
			}
		}
		
		for(String key : getRunningcodetaskmap().keySet()) {
			zztask zztask = getRunningcodetaskmap().get(key);
			Task task = Task.get(getPlayerCode(), zztask.getTaskcode());
			if(task != null && task.isFinish() && !task.isReward()) {
				new TipHandle().updateTip(getPlayerCode(), TipType.活动_征战日志奖励, true);
				return;
			}
		}
		
		new TipHandle().updateTip(getPlayerCode(), TipType.活动_征战日志奖励, false);
	}

	//存储到数据库的方法
	public static void saveToDB(String playerCode) {
		try {
			String key = key(playerCode);
			if (touchBucket(key).isExists()) {
				ActiveModule_征战日志 activeModule_征战日志 = getv(key(playerCode));
				MySQLCacheDAO.setV(key, activeModule_征战日志);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	//从redis移走数据的操作
	public static void removeAllFromRedis(String playerCode) {
		try {
			touchBucket(key(playerCode)).delete();
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}
	//lock --------------------------------------------------------
	@Override
	public String lockKey() {
		return String.format("lock:%s", key(getPlayerCode()));
	}	

}
